<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>消息盒子</title>

    <link rel="stylesheet" href="../../../layui.css?v=1">
    <script src="../../../../jquery.min.js"></script>
    <script src="../../../../../js/path.js"></script>
    <style>
        .layim-msgbox{margin: 15px;}
        .layim-msgbox li{position: relative; margin-bottom: 10px; padding: 0 130px 10px 60px; padding-bottom: 10px; line-height: 22px; border-bottom: 1px dotted #e2e2e2;}
        .layim-msgbox .layim-msgbox-tips{margin: 0; padding: 10px 0; border: none; text-align: center; color: #999;}
        .layim-msgbox .layim-msgbox-system{padding: 0 10px 10px 10px;}
        .layim-msgbox li p span{padding-left: 5px; color: #999;}
        .layim-msgbox li p em{font-style: normal; color: #FF5722;}

        .layim-msgbox-avatar{position: absolute; left: 0; top: 0; width: 50px; height: 50px;}
        .layim-msgbox-user{padding-top: 5px;}
        .layim-msgbox-content{margin-top: 3px;}
        .layim-msgbox .layui-btn-small{padding: 0 15px; margin-left: 5px;}
        .layim-msgbox-btn{position: absolute; right: 0; top: 12px; color: #999;}
    </style>
</head>
<body>

<ul class="layim-msgbox" id="LAY_view"></ul>
<textarea title="消息模版" id="LAY_tpl" style="display:none;">
{{# layui.each(d.data, function(index, item){
  if(item){ }}
    <li data-id="{{ item.id }}"  data-fromGroup="1">
      <a href="#" target="_blank">
        <img src="{{ item.avatar }}" class="layui-circle layim-msgbox-avatar">
      </a>
      <p class="layim-msgbox-user">
        <a href="#" target="_blank">{{ item.username||'' }}</a>
        <span></span>
      </p>
      <p class="layim-msgbox-content">
        <span></span>
      </p>
      <p class="layim-msgbox-btn">
        <button class="layui-btn layui-btn-small" data-type="agree">添加</button>
        <button class="layui-btn layui-btn-small layui-btn-primary" data-type="refuse">忽略</button>
      </p>
    </li>
  {{# }
    });
    }}
</textarea>

<!--
上述模版采用了 laytpl 语法，不了解的同学可以去看下文档：http://www.layui.com/doc/modules/laytpl.html
-->


<script src="../../../../layui.js?v=1"></script>
<script>

    function GetRequest() {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }
    layui.use(['layim', 'flow'], function(){
        var layim = layui.layim
            ,layer = layui.layer
            ,laytpl = layui.laytpl
            ,$ = layui.jquery
            ,flow = layui.flow;

        var cache = {}; //用于临时记录请求到的数据

        //请求消息
        var renderMsg = function(page, callback){

            //实际部署时，请将下述 getmsg.json 改为你的接口地址

            var getRequest = GetRequest();
            var text = getRequest["text"];
            var type = getRequest["type"];
            $.post(baseUrl+'user/getUserOrGroupsByCondition', {
                page: page || 1,
                name:text,
                type:type
            }, function(res){
                if(res.code != 0){
                    return layer.msg(res.msg);
                }
                //记录来源用户信息
                layui.each(res.data, function(index, item){
                    cache[item.from] = item.user;
                });

                callback && callback(res.data, res.pages);
            },"json");
        };

        //消息信息流
        flow.load({
            elem: '#LAY_view' //流加载容器
            ,isAuto: false
            ,end: '<li class="layim-msgbox-tips">暂无更多新消息</li>'
            ,done: function(page, next){ //加载下一页
                renderMsg(page, function(data, pages){
                    console.log(data)
                    console.log(page)
                    console.log(pages)
                    var html = laytpl(LAY_tpl.value).render({
                        data: data
                        ,page: page
                    });
                    next(html, page < pages);
                });
            }
        });

        //打开页面即把消息标记为已读
        /*
        $.post('/message/read', {
          type: 1
        });
        */

        //操作
        var active = {
            //同意
            agree: function(othis){
                var li = othis.parents('li')
                    ,uid = li.data('id')
                    ,from_group = li.data('fromGroup')
                    ,user = cache[uid]
//                    ,avatar = li.
                    alert(JSON.stringify(li.find("a").eq(1).html()))
                //选择分组
                layim.add({
                    type: 'friend'
                    ,username:li.find("a").eq(1).html()
                    ,avatar: li.find("img").attr("src")
                    ,submit: function(group, remark, index){
                        alert(remark)
                        var toUserid = uid;
                        //当前用户的id
                        var userid = localStorage.getItem("userid")
                        //添加到那个分组
                        var groupid = localStorage.getItem("groupid")
                        var content = localStorage.getItem("content")
                        $.post(baseUrl+'user/addUser', {
                            toId:toUserid,
                            userId:userid,
                            groupId:groupid,
                            content:content
                        }, function(res){
                            if(res.code != 0){
                                return layer.msg(res.msg);
                            }else {
                                layer.open({

                                })
                            }
                            //记录来源用户信息
//                            layui.each(res.data, function(index, item){
//                                cache[item.from] = item.user;
//                            });
//
//                            callback && callback(res.data, res.pages);
                        },"json");

                        layer.msg('好友申请已发送，请等待对方确认', {
                            icon: 1
                            ,shade: 0.5
                        }, function(){
                            layer.close(index);
                        });

                        //通知对方
                        /*
                        $.post('/im-applyFriend/', {
                          uid: info.uid
                          ,from_group: group
                          ,remark: remark
                        }, function(res){
                          if(res.status != 0){
                            return layer.msg(res.msg);
                          }
                          layer.msg('好友申请已发送，请等待对方确认', {
                            icon: 1
                            ,shade: 0.5
                          }, function(){
                            layer.close(index);
                          });
                        });
                        */
                    }
                });
//                layer.open({
//                    type: 2 //此处以iframe举例
//                    ,title: '当你选择该窗体时，即会在最顶端'
//                    ,area: ['500px', '300px']
//                    ,shade: 0
//                    ,maxmin: true
//                    ,offset: "auto"
//                    ,content:   layui.cache.dir + 'css/modules/layim/html/select.html?adduserid='+uid
//                    ,btn: ['确定', '关闭'] //只是为了演示
//                    ,yes: function(){
//                        //添加的好友id
//                        var toUserid = uid;
//                        //当前用户的id
//                        var userid = localStorage.getItem("userid")
//                        //添加到那个分组
//                        var groupid = localStorage.getItem("groupid")
//                        var content = localStorage.getItem("content")
//                        //请求添加好友

//
//                    }
//                    ,btn2: function(){
//                        layer.close();
//                    }
//                    ,zIndex: layer.zIndex //重点1
//                    ,success: function(layero){
//                        layer.setTop(layero); //重点2
//                    }
//                });
//                alert(JSON.stringify(uid))
//                alert(localStorage.getItem("userid"))

            }
            //拒绝
            ,refuse: function(othis){
                var li = othis.parents('li')
                    ,uid = li.data('uid');
                console.log(li.data('uid'));
                console.log(li.data('id'));
                layer.confirm('确定拒绝吗？', function(index){
                    $.post('/im/refuseFriend', {
                        uid: uid //对方用户ID
                    }, function(res){
                        if(res.code != 0){
                            return layer.msg(res.msg);
                        }
                        layer.close(index);
                        othis.parent().html('<em>已拒绝</em>');
                    });
                });
            }
        };
        $('body').on('click', '.layui-btn', function(){
            var othis = $(this), type = othis.data('type');
            active[type] ? active[type].call(this, othis) : '';
        });
    });
</script>
</body>
</html>
